<template>
  <div class="activity-list-container">
  <header class="header">
	<button @click="logout" class="tuichu">登出</button>
  </header>
    <h1>活动列表</h1>
    <div class="table-container">

      <a-table :dataSource="approvedActivities" :columns="columns">
        <template #action="{ record }">
          <a-button type="link" @click="showDetails(record.activityId)">详情</a-button>
		  <a-button type="link" @click="jieshu(record.activityId)" v-if="isOrganizer && record.reviewStatus == 'approved'">结束活动</a-button>
		  <a-button type="link" v-if="record.reviewStatus != 'approved'" style="color: red;">活动已结束</a-button>
        </template>
      </a-table>
    </div>

    <a-modal v-model:visible="detailsModalVisible" title="活动详情" @ok="handleOk" @cancel="handleCancel">
      <p><strong>活动名称:</strong> {{ activityDetails?.activity?.name }}</p>
      <p><strong>地点:</strong> {{ activityDetails?.activity?.location }}</p>
      <p><strong>时间:</strong> {{ activityDetails?.activity?.time }}</p>
	  <p><strong>活动照片:</strong> 
	  <div>
	  	<a-image :src="item" v-for="item in fileUrls" style="width: 100px;height: 100px;"/>
	  </div></p>
      <p><strong>内容:</strong> {{ activityDetails?.activity?.content }}</p>
      <!-- <p><strong>审核状态:</strong> {{ activityDetails?.activity?.reviewStatus }}</p> -->
      <p><strong>活动学分:</strong> {{ activityDetails?.activity?.xuefen }}</p>
      <p><strong>参与活动人数:</strong>{{activityDetails?.volunteers?.length}}</p>
	  <p v-if="!isOrganizer && hasJoined"><strong>打卡状态:</strong>{{isDaKa?'已打卡':'未打卡'}}</p>
      <p><strong>志愿者:</strong></p>
      <ul>
        <li v-for="volunteer in activityDetails?.volunteers" :key="volunteer.userId">
          {{ volunteer.name }} ({{ volunteer.phone }})
        </li>
      </ul>
	  <a-button type="primary" @click="showConfirm()" v-if="!isOrganizer && !hasJoined && !isReviewStatus">申请报名</a-button>
	  <a-button type="primary" @click="daka()" v-if="!isOrganizer && hasJoined && !isDaKa && !isReviewStatus" style="margin-right: 20px;">打卡</a-button>
	  <a-button type="primary" @click="showtuichuDetails()" v-if="!isOrganizer && hasJoined && !isReviewStatus">申请退出</a-button>
	  <a-button type="link" v-if="isReviewStatus" style="color: red;">活动已结束</a-button>
    </a-modal>

    <a-modal title="确认报名" v-model:visible="confirmModalVisible" @ok="joinActivity(1)" @cancel="handleCancel">
      <p>你确定要报名参加这个活动吗？</p>
	  <p><strong>申请原因:</strong>
		<a-input v-model:value="shenqingYuanyin"/>
	  </p>
    </a-modal>
	<a-modal title="确认退出活动" v-model:visible="tuichuModalVisible" @ok="joinActivity(3)" @cancel="handleCancel">
	  <p>你确定要退出这个活动吗？</p>
	  <p><strong>退出原因:</strong>
	  		<a-input v-model:value="tuichuYuanyin"/>
	  </p>
	</a-modal>

<!--    <a-button class="back-button" type="default" @click="goBack">返回主页</a-button>-->
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import axios from '../api/request.ts';
import { Table as aTable, Modal as aModal, Button as aButton, Image as aImage, message } from 'ant-design-vue';
import { useUserStore } from '../stores/user.ts';
import router from '@/router';

const activities = ref([]);
const shenqingYuanyin = ref('');
const tuichuYuanyin = ref('');
const approvedActivities = ref([]);
const activityDetails = ref(null);
const detailsModalVisible = ref(false);
const confirmModalVisible = ref(false);
const tuichuModalVisible = ref(false);
const userStore = useUserStore();
const isLoggedIn = !!userStore.userId;
const hasJoined = ref(false);
const isDaKa = ref(false);
const isReviewStatus = ref(false);
const isOrganizer = ref(userStore.userType === 'event_organizer');
const fileUrls = ref([]);

const columns = [
  { title: '活动名称', dataIndex: 'name', key: 'name' },
  { title: '地点', dataIndex: 'location', key: 'location' },
  { title: '时间', dataIndex: 'time', key: 'time' },
  { title: '活动学分', dataIndex: 'xuefen', key: 'xuefen' },
  { title: '内容', dataIndex: 'content', key: 'content' },
  // { title: '审核状态', dataIndex: 'reviewStatus', key: 'reviewStatus' },
  {
    title: '操作',
    key: 'action',
    slots: { customRender: 'action' },
  },
];

const fetchActivities = async () => {
  try {
    const response = await axios.get('/activities');
    approvedActivities.value = response.data;
    // 只保留审核状态为 "approved" 的活动
    // approvedActivities.value = activities.value.filter(activity => activity.reviewStatus === 'approved');
  } catch (error) {
    console.error('Error fetching activities:', error);
  }
};

const showDetails = async (activityId) => {
  try {
    const response = await axios.get(`/activities/${activityId}`);
    activityDetails.value = response.data;
	if(activityDetails.value.activity.reviewStatus != 'approved'){
		isReviewStatus.value = true
	} else {
		isReviewStatus.value = false
	}
	if(activityDetails.value.activity.imageUrls){
		console.log('111:',activityDetails.value.activity.imageUrls)
		fileUrls.value = activityDetails.value.activity.imageUrls.split(';')
	}
    detailsModalVisible.value = true;
    // Reset hasJoined state
    hasJoined.value = false;
    // Check if user has already joined
    const userResponse = await axios.get(`/activities/${activityId}/participants`);
    const participants = userResponse.data;
    if (participants.some(a => a.userId == userStore.userId)) {
      hasJoined.value = true;
    }
	const res = await axios.post(`/activities/isdaka/${activityId}/${userStore.userId}`);
	const userAct = res.data;
	if (userAct.dakaSatus == 1) {
	  isDaKa.value = true;
	}
	
  } catch (error) {
    console.error('Error fetching activity details:', error);
  }
};

const showConfirm = () => {
  confirmModalVisible.value = true;
};

const showtuichuDetails = () => {
  tuichuModalVisible.value = true;
};

const handleOk = () => {
  detailsModalVisible.value = false;
};

const handleCancel = () => {
  confirmModalVisible.value = false;
  detailsModalVisible.value = false;
  tuichuModalVisible.value = false;
};
const logout = () => {
  userStore.logout();
  router.push('/');
};
const jieshu = async (id) => {
  try {
	  await axios.get(`/activities/jieshuActivity/${id}`);
	  message.success('结束活动成功');
  } catch (error) {
    console.error('Error joining activity:', error);
	message.error('结束活动失败');
  }
  fetchActivities()
};
const daka = async () => {
  try {
	  await axios.post(`/activities/daka/${activityDetails.value.activity.activityId}/${userStore.userId}`);
	  message.success('活动打卡成功');
  } catch (error) {
    console.error('Error joining activity:', error);
	message.error('活动打卡失败');
  }
  handleCancel();
};
const joinActivity = async (status) => {
  try {
	  if(status == 1 && !shenqingYuanyin.value){
	  	message.error('申请原因不能为空');
	  } else if(status == 3 && !tuichuYuanyin.value){
	  	message.error('退出原因不能为空');
	  } else {
		  if(status == 1){
			  const res = await axios.post(`/activities/${activityDetails.value.activity.activityId}/join`, null, {
			    params: {
			        userId: userStore.userId,
					status: status,
					shenqingYuanyin: shenqingYuanyin.value,
			    }
			  });
			  if(res.data.status == 1){
			  	message.success('申请报名成功');
			  } else if(res.data.status == -1){
				  message.error('用户已参加过该活动，不能重复申请');
			  }
		  } else {
			  const res = await axios.post(`/activities/tuiUserActivity/${activityDetails.value.activity.activityId}/${userStore.userId}`, null, {
			    params: {
					tuichuYuanyin: tuichuYuanyin.value
			    }
			  });
			  console.log('res:',res)
			  if(res.data){
			  	message.success('申请退出成功');
			  }
		  }
		  handleCancel();
	  }
  } catch (error) {
    console.error('Error joining activity:', error);
	if(status == 1){
		message.error('申请报名失败');
		confirmModalVisible.value = false;
	} else {
		message.error('申请退出失败');
		tuichuModalVisible.value = false;
	}
  }
};

// const goBack = () => {
//   router.push('/home');
// };

fetchActivities();
</script>
<style>
.header {
  display: flex;
  justify-content: flex-end;;
  align-items: center;
  padding: 16px;
  background-color: #f0f2f5;
  border-bottom: 1px solid #dcdcdc;
}
</style>

<!--<style scoped>-->
<!--/* 外层容器，用于包裹整个活动列表页面，使内容居中 */-->
<!--.activity-list-container {-->
<!--  display: flex;-->
<!--  flex-direction: column;  /* 使内容垂直排列 */-->
<!--  align-items: center;     /* 水平居中 */-->
<!--  padding: 20px;           /* 容器内填充 */-->
<!--  background-color: #f0f2f5; /* 背景颜色 */-->
<!--}-->

<!--/* 表格容器，限制表格宽度并使其居中 */-->
<!--.table-container {-->
<!--  width: 100%;-->
<!--  max-width: 800px;        /* 最大宽度 */-->
<!--  background-color: white; /* 表格背景色 */-->
<!--  padding: 20px;           /* 表格容器内填充 */-->
<!--  border-radius: 8px;      /* 圆角 */-->
<!--  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 阴影 */-->
<!--}-->

<!--/* 返回主页按钮，居中显示 */-->
<!--.back-button {-->
<!--  margin-top: 20px;        /* 按钮顶部间距 */-->
<!--}-->

<!--.logo {-->
<!--  width: 100px;             /* 设置logo图片的宽度 */-->
<!--  margin-bottom: 20px;      /* 图片下方的间距 */-->
<!--}-->
<!--</style>-->
